package com.etone.smartAudit.config;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author: sovy
 * @date: 2020/9/27
 * @description:
 */
@Configuration
public class ElasticSearchConfig {
    @Value("${es.host:localhost}")
    private String host;

    @Value("${es.port:9200}")
    private Integer port;

    @Value("${es.scheme:http}")
    private String scheme;

    @Value("${es.user:elastic}")
    private String user;

    @Value("${es.password}")
    private String password;


    @Bean
    public RestHighLevelClient restHighLevelClient() {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

        //账号密码校验
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(user, password));
        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(RestClient.builder(new HttpHost(host, port, scheme)).setHttpClientConfigCallback((httpClientBuilder) -> {
            httpClientBuilder.disableAuthCaching();
            return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        }));
        return restHighLevelClient;
    }
}
